<template>
	<view class="uni-flex-column container">
		<view class="content">
			<view class="goods">
				<view class="uni-flex uni-align-center info-box">
					<image :src="decodedItemImg" mode="aspectFill" class="item-image"></image>
					<text class="title">{{ orderInfo.itemName }}</text>
				</view>
				<view class="uni-flex service">
					<text class="text1">服务效率</text>
					<uni-rate v-model="info.efficiency" activeColor="#2F80ED" margin="6" />
					<text class="text2">{{ rateList[info.efficiency] }}</text>
				</view>
				<view class="uni-flex service">
					<text class="text1">服务效果</text>
					<uni-rate v-model="info.effect" activeColor="#2F80ED" margin="6" />
					<text class="text2">{{ rateList[info.effect] }}</text>
				</view>
				<view class="uni-flex service">
					<text class="text1">服务态度</text>
					<uni-rate v-model="info.attitude" activeColor="#2F80ED" margin="6" />
					<text class="text2">{{ rateList[info.attitude] }}</text>
				</view>
				<view class="desc-content">
					<uni-easyinput v-model="info.content" type="textarea" :inputBorder="false" maxlength="300"
						placeholder="请描述你对此次服务的使用体验及感受" />
					<uni-file-picker limit="9" mode="grid" :del-icon="true" file-mediatype="image"
						:imageStyles="imageStyles" @success="success" @fail="fail" @select="selectFile">
						<view class="custom-upload">
							<uni-icons type="camera" size="26"></uni-icons>
							<text class="text">添加图片</text>
						</view>
					</uni-file-picker>
				</view>
			</view>
			<view class="select-box">
				<uni-data-checkbox multiple v-model="info.isAnonymous" :localdata="array"
					class="radio"></uni-data-checkbox>
			</view>
		</view>
		<view class="bottom">
			<view class="submit" @click="submit">提交</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive,
		computed
	} from "vue";
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		qiNiuFileUpload
	} from "@/utils/qiniu.js";
	import {
		orderEvalutate
	} from "@/api/consumerOrder.js";

	const rateList = ["请评价", "极差", "不满意", "一般", "比较满意", "非常满意"];
	const imageValue = ref([]);
	const info = reactive({
		orderId: "",
		efficiency: 0,
		effect: 0,
		attitude: 0,
		content: "",
		imageUrls: ",",
		isAnonymous: [1]
	});

	const checkbox1 = ref([]);
	const array = [{
		text: "匿名评价",
		value: 1
	}];

	const imageStyles = {
		width: 64,
		height: 64,
		border: {
			width: 1,
			style: "dashed",
			color: "#CFCFCF",
			radius: 4
		}
	};

	const success = (e) => {
		console.log(e, "1");
	};

	const selectFile = (e) => {
		console.log(e, "2");
		imageValue.value = e.tempFilePaths || [];
	};
	const fail = (e) => {};

	// 上传头像到七牛云
	const uploadAvatarToQiNiu = async () => {
		let files = [];
		imageValue.value.forEach((item) => {
			files.push({
				path: item,
				key: `images/avatar/${info.orderId}/${Date.now()}_${Math.floor(Math.random() * 10)}.png`
			});
		});
		return new Promise((resolve, reject) => {
			qiNiuFileUpload(
				files,
				(successUrl) => {
					console.log("七牛返回URL", successUrl);
					resolve(successUrl);
				},
				(error) => {
					console.error("七牛上传失败", error);
					reject(error);
				}
			);
		});
	};

	const submit = async () => {
		uni.showLoading({
			title: "保存中...",
			mask: true
		});

		try {
			// 先上传图片
			if (imageValue.value && imageValue.value.length > 0) {
				info.imageUrls = await uploadAvatarToQiNiu();
			}

			const params = {
				...info,
				isAnonymous: info.isAnonymous.length ? 1 : 0
			};

			const response = await orderEvalutate(params);

			if (response?.code === 200) {
				uni.showToast({
					title: "评价成功",
					icon: "success"
				});

				// 获取上一页实例并刷新
				const pages = getCurrentPages();
				if (pages.length > 1) {
					const prevPage = pages[pages.length - 2];

					// 使用 uni.$emit 触发事件（推荐方式）
					uni.$emit('refreshOrderList');

					// 或者确保使用正确的路由路径来匹配
					if (prevPage.route === 'pages/order/consumerOrder/orderList') {
						// 使用 setTimeout 确保在页面跳转前触发
						setTimeout(() => {
							// 方式1：尝试调用页面方法（如果暴露了）
							if (prevPage.refreshList) {
								prevPage.refreshList();
							}
							// 方式2：触发自定义事件
							prevPage.$vm?.reload?.();
						}, 300);
					}
				}

				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		} catch (err) {
			uni.showToast({
				title: "评价失败",
				icon: "error"
			});
		} finally {
			uni.hideLoading();
		}
	};
	const orderInfo = reactive({
		itemName: "",
		itemImg: ""
	});

	// 计算属性用于解码图片URL
	const decodedItemImg = computed(() => {
		return decodeURIComponent(orderInfo.itemImg || '');
	});

	onLoad((option) => {
		info.orderId = option.id;
		orderInfo.itemName = option.itemName;
		// 解码接收到的图片URL
		orderInfo.itemImg = option.itemImg || '';
		console.log('接收到的参数', option);
		console.log('解码后的图片URL', decodedItemImg.value);
	});
</script>

<style lang="scss" scoped>
	.container {
		background: #f5f5f5;
		height: 100vh;
		box-sizing: border-box;
		padding-top: 24rpx;

		.content {
			flex: 1;
			overflow-y: auto;

			.goods {
				margin: 0 24rpx;
				padding: 31rpx 35rpx;
				background: #fff;
				border-radius: 20rpx;
				box-sizing: border-box;

				.info-box {
					margin-bottom: 38rpx;

					.item-image {
						width: 64rpx;
						height: 64rpx;
						border-radius: 8rpx;
					}

					.title {
						flex: 1;
						margin-left: 24rpx;
						font-weight: 500;
						font-size: 28rpx;
						color: #333333;
					}
				}

				.service {
					margin-bottom: 24rpx;

					.text1 {
						font-size: 30rpx;
						font-weight: 500;
						color: #333333;
						margin-right: 40rpx;
						width: 140rpx;
					}

					.text2 {
						font-size: 28rpx;
						color: #333333;
						margin-left: 40rpx;
					}
				}
			}

			.desc-content {
				margin-top: 5rpx;
				padding: 32rpx;
				background: #f8f8f8;
				border-radius: 20rpx;
				box-sizing: border-box;

				:deep(.uni-easyinput__content) {
					margin-bottom: 12rpx;
					background-color: #f8f8f8 !important;

					.uni-easyinput__content-textarea {
						height: 270rpx;
					}
				}

				.custom-upload {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					width: 115rpx;
					height: 115rpx;
					border-radius: 10rpx;
					border: 1rpx dashed #cfcfcf;

					.text {
						font-weight: 400;
						font-size: 22rpx;
						color: #999999;
					}
				}
			}

			.select-box {
				margin-top: 24rpx;
				margin-left: 24rpx;

				.radio {
					:deep(.checkbox__inner) {
						width: 30rpx !important;
						height: 30rpx !important;
						border-radius: 50% !important;
					}

					:deep(.checklist-text) {
						margin-left: 24rpx !important;
						font-weight: 400 !important;
						font-size: 28rpx !important;
						color: #999999 !important;
					}
				}
			}
		}

		.bottom {
			background: #fff;
			padding: 20rpx 24rpx;

			.submit {
				width: 100%;
				height: 88rpx;
				line-height: 88rpx;
				text-align: center;
				background: #2f80ed;
				border-radius: 44px;
				color: white;
				font-size: 30rpx;
			}
		}
	}
</style>